package channel

import (
	"errors"
	"fmt"
	"micro-rulego/internal/biz/device"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/google/uuid"
)

type EntryConn struct {
	connc  device.DeviceManager
	devID  device.DeviceID
	connID device.ConnectID
}

func (ce *EntryConn) ID() EntryID {
	return EntryID(uuid.NewSHA1(uuid.NameSpaceURL, []byte(fmt.Sprintf("%d%d", ce.devID, ce.connID))).ID())
}

func (ce *EntryConn) DevID() uint32 {
	return uint32(ce.devID)
}

func (ce *EntryConn) ConnID() uint32 {
	return uint32(ce.connID)
}

func (ce *EntryConn) Transmit(data []byte) error {
	return ce.connc.DeviceConnectTransimit(ce.devID, ce.connID, data)
}

func (ce *EntryConn) Receive() ([]byte, error) {
	if ce == nil || ce.connc == nil {
		log.Error("entry conn or device manager is nil")
		return nil, errors.New("entry conn or device manager is nil")
	}
	return ce.connc.DeviceConnectReceive(ce.devID, ce.connID)
}

func NewEntryConn(connc device.DeviceManager, devID device.DeviceID, connID device.ConnectID) ChannelEntry {
	return &EntryConn{
		connc:  connc,
		devID:  devID,
		connID: connID,
	}
}
